package com.example.administrator.show.photo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.show.HomeChildFragment;
import com.example.administrator.show.PostNetData;
import com.example.administrator.show.R;
import com.example.administrator.show.data.ImageList;
import com.example.administrator.show.utils.FaceRect;
import com.example.administrator.show.utils.ImageResizer;
import com.faceplusplus.api.FaceDetecter;
import com.facepp.error.FaceppParseException;
import com.facepp.http.HttpRequests;
import com.facepp.http.PostParameters;
import com.iflytek.cloud.FaceDetector;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * @author yexiuliang
 * @page
 * @data 2016-11-13
 */

public class PhotoFragment extends HomeChildFragment implements View.OnClickListener {


    private String fileSrc;
    private Button btSave, btPhoto;
    private Button bt_person,bt_cihui,bt_share;
    private ImageView ivPhoto, ivHeadwear;
    private ImageView ivHeadwearToPhoto;
    private RelativeLayout rlEditPhoto;
    private LinearLayout ll_header;
    final int  HANDLE_TYPE = 10;
    final int  HANDLE_ERROR = 13;
    private  String tag = "photo";
    /// private  int

    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 1;



    /***************
     * 人脸识别相关
     *************************/
    private Bitmap curBitmap = null;
    HandlerThread detectThread = null;
    Handler detectHandler = null;
    FaceDetecter detecter = null;
    HttpRequests request = null;// 在线api
    private static Bitmap head;
    private Handler mHandler;
    private String[][] datalist;
    private HashMap<String, String> listItem;
    private String message;
    private HorizontalScrollView horizontalScrollView;
    private DisplayMetrics dm;
    private int LIE =8;
    private int NUM = 4; // 每行显示个数
    private int LIEWIDTH;//每列宽度
    private String cur_face_id;
    private String cur_face_cihui_url;
    private String cur_face_renwu_url;


    private titleSelectInterface mSelectInterface;

    private FaceDetector mFaceDetector;
    private Bitmap mImage;
    private Toast mToast;
    private FaceRect[] mFaces;
    private Uri img_path;
    private Uri save_uri;
    private Bitmap bmp;


    //** 构建跳转到人物和测试的页面
    public interface titleSelectInterface {
        public void setweburl(String title);
        public void goshare(Uri save_uri,Bitmap bmp);

    }

        //** 构建跳转到分享的接口
    @Override
    protected View onCreateContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_photo, container, false);
    }

    @Override
    protected void onInit() {
        super.onInit();
        new Thread(runnable).start();

       /// initlist();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onFindViews() {
        super.onFindViews();
        btSave = (Button) mContentView.findViewById(R.id.bt_save);
        btPhoto = (Button) mContentView.findViewById(R.id.bt_take_photo);
        bt_person = (Button) mContentView.findViewById(R.id.bt_person);
        bt_cihui = (Button) mContentView.findViewById(R.id.bt_cihui);
        bt_share = (Button) mContentView.findViewById(R.id.bt_share);


        ivHeadwear = (ImageView) mContentView.findViewById(R.id.iv_headwear);
        ivPhoto = (ImageView) mContentView.findViewById(R.id.iv_get_photo);
        ivHeadwearToPhoto = (ImageView) mContentView.findViewById(R.id.iv_headwear_to_photo);
        rlEditPhoto = (RelativeLayout) mContentView.findViewById(R.id.rl_edit_photo);
        ll_header = (LinearLayout) mContentView.findViewById(R.id.ll_header);



      //  horizontalScrollView = (HorizontalScrollView) mContentView.findViewById(R.id.scrollView);
      ///  horizontalScrollView.setHorizontalScrollBarEnabled(false);// 隐藏滚动条
    }


    /**
     * 选择图片后返回
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ImageList imageList) {
        if (imageList != null && imageList.has) {

             img_path =Uri.fromFile(new File(imageList.imageList.get(0).path));
            Glide.with(this)                             //配置上下文
                    .load(img_path)      //设置图片路径(fix #8,文件名包含%符号 无法识别和显示)
                    .into(ivPhoto);
        curBitmap =  ((BitmapDrawable)ivPhoto.getDrawable()).getBitmap();


           /// save_img_(curBitmap);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void picEventBus(Bitmap  bitmap){
        if(bitmap != null ) {
            curBitmap = bitmap; // 给到当前照片


            ivPhoto.setImageBitmap(bitmap);

          ///  save_img_(curBitmap);
        }
    }
/*

* 图片返回后保存到合适的路径
*
* */
    /*
  public   void save_img_( Bitmap bmp){

      // 若返回数据不为null，保存至本地，防止裁剪时未能正常保存
      if(null != bmp){
          FaceUtil.saveBitmapToFile(getContext(), bmp);
      }

      // 获取图片保存路径
      fileSrc = FaceUtil.getImagePath(getContext());
      // 获取图片的宽和高
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      mImage = BitmapFactory.decodeFile(fileSrc, options);

      // 适当压缩图片可以加快检测速度
      options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
              (double) options.outWidth / 1024f,
              (double) options.outHeight / 1024f)));
      options.inJustDecodeBounds = false;
      mImage = BitmapFactory.decodeFile(fileSrc, options);

      // 部分手机会对图片做旋转，这里检测旋转角度
      int degree = FaceUtil.readPictureDegree(fileSrc);
      if (degree != 0) {
          // 把图片旋转为正的方向
          mImage = FaceUtil.rotateImage(degree, mImage);
      }

      ivPhoto.setImageBitmap(mImage);
      // 清除上次人脸检测结果
      mFaces = null;

   }
*/


    private void getScreenDen() {
        dm = new DisplayMetrics();
        /// getWindowManager().getDefaultDisplay().getMetrics(dm);
    }

    @Override
    protected void onBindListener() {
        super.onBindListener();
        btPhoto.setOnClickListener(this);
        btSave.setOnClickListener(this);
        bt_person.setOnClickListener(this);
        bt_cihui.setOnClickListener(this);
        bt_share.setOnClickListener(this);


        ivHeadwearToPhoto.setVisibility(View.GONE);
       // ivHeadwear.setOnClickListener(this);
    }

    @Override
    protected void onInitViewData() {
        super.onInitViewData();
/////讯飞识别
     ///   mFaceDetector = FaceDetector.createDetector(getContext(), null);

    //人脸识别相关
        mHandler = new Handler(Looper.getMainLooper());
        detectThread = new HandlerThread("detect");
        detectThread.start();
        detectHandler = new Handler(detectThread.getLooper());

      ///  curBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tmd);

        detecter = new FaceDetecter();
        detecter.init(getContext(), "16af7501327961524d2a1f4bcf81af84");

    ///准备头饰
        head = BitmapFactory.decodeResource(getResources(), R.mipmap.edit_image_simple1);
        //FIXME 替换成申请的key
        request = new HttpRequests("16af7501327961524d2a1f4bcf81af84",
                "cHOEHT_TvvUgLJ8Czp1uWfjJle3DCMvH");



        mToast = Toast.makeText(getContext(), "", Toast.LENGTH_SHORT);


        
    }


    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case HANDLE_TYPE:
                   initlist();
                    break;

                case HANDLE_ERROR:
                    Toast.makeText(getContext(), "失败"+"\n"+ message,
                            Toast.LENGTH_SHORT).show();

                    break;
            }

        }

        ;
    };

    Runnable runnable = new Runnable() {
        public void run() {
         //   Drawable drawable = null;
            int re = getdata();


            Log.v("run", "initv");

            if(re == 1){
                Message msg = handler.obtainMessage();
                msg.what = HANDLE_TYPE;

                handler.sendMessage(msg);
            }else{
                Message msg = handler.obtainMessage();
                msg.what = HANDLE_ERROR;

                handler.sendMessage(msg);
            }
        }
    };


    private int getdata() {
        try {


            String rev = PostNetData.postResultForHttpGet();

            if (rev.equals("") | rev == null) {
                return 0;
            }
            JSONObject obj = new JSONObject(rev);


            JSONArray firstList = obj.getJSONArray("data");
            Log.v("firstlist",firstList.toString());
            int length = firstList.length();
            datalist = new String[length][];
            //  logobit = new Bitmap [length];
            for (int i = 0; i < length; i++) {
                JSONObject oj = firstList.getJSONObject(i);
                int idlen = oj.length();
                //定义第二维长度
                datalist[i]=new String[idlen];
                datalist[i][0] = oj.getString("id").toString();
                datalist[i][1] = oj.getString("icon").toString();
                datalist[i][2] = oj.getString("us_name").toString();
                datalist[i][3] = oj.getString("cn_name").toString();
                datalist[i][4] = oj.getString("renwu_href").toString();

                datalist[i][5] = oj.getString("png_href").toString();
                datalist[i][6] = oj.getString("cihui_href").toString();
            }

            return 1;

        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }


    public void initlist() {


        final GridView listView1 = (GridView) getView().findViewById(R.id.list_view_id);
        List<Map<String, String>> listItems = new ArrayList<Map<String, String>>();
        //for (int i = 0; i < mount; i+2) {
        int datalen=0;
        if(datalist!=null){
            datalen = datalist.length;
        }
        //Log.v("datalist",datalis);
        for (int i = 0; i <datalen; i++) {
            listItem = new HashMap<String, String>();
            listItem.put("png_href",datalist[i][5].toString()); //name[i]);

            Log.v("listItem",listItem.toString());

            listItems.add(listItem);
        }
        // }
        ///    Log.v("datalist",datalist.toString());
        String[] from = {"png_href"};
        int[] to = {R.id.iv_headwear};
        SimpleAdapter simpleAdapter = new MyAdapter(getContext(), listItems, R.layout.iconlist, from, to);
        Log.v("listItems",listItems.toString());
        listView1.setAdapter(simpleAdapter);
        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
               /// renwulistener(position);


                cur_face_id = datalist[position][0];
                cur_face_renwu_url = datalist[position][4];
                cur_face_cihui_url = datalist[position][6];


                  hecheng(position);

            }
        });



         //定义 gridview 的宽度
        ViewGroup.LayoutParams params = listView1.getLayoutParams();
        // dishtype，welist为ArrayList
        int dishtypes = 8; //welist.size();
        params.width = 200 * dishtypes;
        Log.d("看看这个宽度", params.width+""+8);
        listView1.setLayoutParams(params);
        //设置列数为得到的list长度
        listView1.setNumColumns(8);
        Log.v("listItems","end");

    }



    
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //保存
            case R.id.bt_save:
                saveView(rlEditPhoto);
               // ivHeadwearToPhoto.setVisibility(View.GONE);
                break;
            //拍照
            case R.id.bt_take_photo:
               /// paizhao();

                break;
            //点击人物
            case R.id.bt_person:
               /// getActivity().bt_person();
                Log.v("photo","人物开始");
               mSelectInterface.setweburl(cur_face_renwu_url);
                break;

            //点击词汇测试
            case R.id.bt_cihui:
                /// getActivity().bt_person();
                Log.v("photo","词汇开始");
                mSelectInterface.setweburl(cur_face_cihui_url);

                break;


            //点击分享案例 ，跳转到分享的页面
            case R.id.bt_share:
                /// getActivity().bt_person();
                Log.v("photo","跳转到分享页面");
                mSelectInterface.goshare( save_uri,bmp);

                break;

            //点击头饰效果
            case R.id.iv_headwear:
          //点击头像合成去别的地方了
                break;

            default:

                Log.v("photo","有点击产生"+view.getId());
                break;
        }
    }


/*
   public  void   renwulistener( View v){

        Log.v("renwu","人物开始");

       mSelectInterface.onTitleSelect(cur_face_renwu_url);

    }
*/

/*
public void hecheng(int position) {
    if (null != mImage) {
        if(mFaceDetector == null) {

            showTip("本SDK不支持离线人脸检测");

           return;
        }



         Log.v(tag,"启动人脸识别");
        // 启动图片人脸检测
        String result = mFaceDetector.detectARGB(mImage);



        // 解析人脸结果
        mFaces = ParseResult.parseResult(result);

        Log.v(tag,mFaces.toString());


        if (null != mFaces && mFaces.length > 0) {
            drawFaceRects(mFaces);
        } else {
            // 在无人脸的情况下，判断结果信息
            int errorCode = 0;
            JSONObject object;
            try {

                Log.v("photo:",result.toString());
                object = new JSONObject(result);
                errorCode = object.getInt("ret");
            } catch (JSONException e) {
            }
            // errorCode!=0，表示人脸发生错误，请根据错误处理
            if(ErrorCode.SUCCESS == errorCode) {
                showTip("没有检测到人脸");
            } else {
                showTip("检测发生错误，错误码："+errorCode);
            }



        }




    }
}
*/


    private void drawFaceRects(FaceRect[] faces) {
        Paint paint = new Paint();
        paint.setColor(Color.YELLOW);
        paint.setStrokeWidth(Math.max(mImage.getWidth(), mImage.getHeight()) / 100f);
        paint.setStyle(Paint.Style.STROKE);

        Bitmap bitmap = Bitmap.createBitmap(mImage.getWidth(),
                mImage.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(mImage, new Matrix(), null);

        for (FaceRect face: faces) {
            canvas.drawRect(face.bound, paint);

            if (null != face.point) {
                for (Point p: face.point) {
                    canvas.drawPoint(p.x, p.y, paint);
                }
            }
        }

       ((ImageView) getView().findViewById(R.id.iv_get_photo)).setImageBitmap(bitmap);
    }


    public void hecheng(int position){
        Log.v(tag,"合成开始");
      //  ivHeadwearToPhoto.setVisibility(View.VISIBLE);
        //获取要合成的图片
      //  ivHeadwearToPhoto.setImageResource(R.mipmap.edit_image_simple1);
        if (curBitmap == null) {
            Toast.makeText(getContext(), "请先拍照或选择图片", Toast.LENGTH_SHORT).show();
            return;
        }
        detectHandler.post(new Runnable() {
            @Override
            public void run() {

                FaceDetecter.Face[] faceinfo = detecter.findFaces(curBitmap);// 进行人脸检测
                if (faceinfo == null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "未发现人脸信息", Toast.LENGTH_LONG)
                                    .show();
                        }
                    });
                    return;
                }

                Log.v(tag,"人脸数据"+faceinfo.toString());


                //在线api交互
                try {
                    request.offlineDetect(detecter.getImageByteArray(), detecter.getResultJsonString(), new PostParameters());
           Log.v("photo", detecter.getResultJsonString());

                } catch (FaceppParseException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
                final Bitmap bit = getFaceInfoBitmap(faceinfo, curBitmap);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        ivPhoto.setImageBitmap(bit);
                        System.gc();
                    }
                });
            }
        });

    }




    @SuppressLint("SdCardPath")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getContext()).onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            String sdStatus = Environment.getExternalStorageState();
            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                Log.i("TestFile", "SD card is not avaiable/writeable right now.");
                return;
            }
            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
            curBitmap = bitmap;
            ivPhoto.setImageBitmap(bitmap);

        }
    }

    /**
     * 保存view图片到本地
     *
     * @param view
     */
    private void saveView(View view) {

        Log.v("photo","保存图片");

           bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        view.draw(new Canvas(bmp));
        ///生成本地地址，并返回 uri
         save_uri =   saveImageToGallery(getContext(),bmp);


      //  saveImageToGallery(getContext(),bmp);

       // File file = ImageResizer.saveBitmapFile(bmp);
     ///   Toast.makeText(getContext(), "保存成功，在内存卡的cache文件夹中查看", Toast.LENGTH_SHORT).show();



        //Log.v("photo","广播通知相册更新");
        /*
        * 广播通知相册有更新 ,g
        * */
   /*     Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        Log.v("photo",uri.toString());
        intent.setData(uri);
        getContext().sendBroadcast(intent);
    */


        btSave.setVisibility(View.GONE);
        ll_header.setVisibility(View.GONE);
        bt_person.setVisibility(View.VISIBLE);
        bt_cihui.setVisibility(View.VISIBLE);
        bt_share.setVisibility(View.VISIBLE);


    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mSelectInterface = (titleSelectInterface) activity;
        } catch (Exception e) {
            throw new ClassCastException(activity.toString() + "must implement  ");
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        detecter.release(getContext());// 释放引擎
    }

    public static Bitmap getFaceInfoBitmap(FaceDetecter.Face[] faceinfos,
                                           Bitmap oribitmap) {
        Bitmap tmp;
        float aim_height ,aim_width;
///整体系数
       /// float xishu ;
        tmp = oribitmap.copy(Bitmap.Config.ARGB_8888, true);

        Canvas localCanvas = new Canvas(tmp);
        Paint localPaint = new Paint();
        localPaint.setColor(0xffff0000);
        localPaint.setStyle(Paint.Style.STROKE);
        aim_height = oribitmap.getHeight();
        aim_width = oribitmap.getWidth();

        for (FaceDetecter.Face localFaceInfo : faceinfos) {
            float left, right, top, bottom;
            float heigt, width;

            left = oribitmap.getWidth() * localFaceInfo.left;
            right = oribitmap.getWidth() * localFaceInfo.right;
            top = oribitmap.getHeight() * localFaceInfo.top;
            bottom = oribitmap.getHeight() * localFaceInfo.bottom;
            heigt = bottom - top;
            width = right - left;

            float ratio = 1.3f * heigt / head.getHeight();
            Matrix matrix = new Matrix();
            matrix.postScale(ratio, ratio); //长和宽放大缩小的比例
            Bitmap resizeBmp = Bitmap.createBitmap(head, 0, 0, head.getWidth(), head.getHeight(), matrix, true);
            //  Bitmap resizeBmp = Bitmap.createBitmap(head,0,0,oribitmap.getWidth(),oribitmap.getHeight());
          /*  localCanvas.drawBitmap(resizeBmp, oribitmap.getWidth() * localFaceInfo.left, 2 * oribitmap.getHeight() *
                    localFaceInfo.top - oribitmap.getHeight()
                    * localFaceInfo.bottom, null); */
            Log.v("photo","图片宽高：width:"+aim_width+"height:"+aim_height);
            Log.v("photo","识别出的人脸范围：left:"+left+"r:"+right+"top:"+heigt+"bottom:"+width);
            Log.v("photo","height:"+heigt);
            Log.v("photo","width:"+width);
            Log.v("photo","附加图： height:"+head.getHeight()+"width:"+head.getWidth());
            localCanvas.drawBitmap(resizeBmp,left +width/2 - head.getWidth()*ratio/2,  2 * oribitmap.getHeight() *
                    localFaceInfo.top - oribitmap.getHeight()
                    * localFaceInfo.bottom, null);
        }
        return tmp;
    }

    public static Bitmap getScaledBitmap(String fileName, int dstWidth) {
        BitmapFactory.Options localOptions = new BitmapFactory.Options();
        localOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(fileName, localOptions);
        int originWidth = localOptions.outWidth;
        int originHeight = localOptions.outHeight;

        localOptions.inSampleSize = originWidth > originHeight ? originWidth / dstWidth
                : originHeight / dstWidth;
        localOptions.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(fileName, localOptions);
    }





    public static Uri  saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
          /*
        try {

           String  av =  MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);

           /// Log("photo",av.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
       */
        // 最后通知图库更新



        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        ///Log.v("photo",uri.toString());
        intent.setData(uri);
        context.sendBroadcast(intent);
        return  uri;
    }


    private void showTip(final String str) {
        mToast.setText(str);
        mToast.show();
    }


    public class MyAdapter extends SimpleAdapter {




        public MyAdapter(Context context, List<? extends Map<String, ?>> data,
                         int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
            // TODO Auto-generated constructor stub
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            final ImageView im = (ImageView)view.findViewById(R.id.iv_headwear);



          //  if (convertView == null) {

              view.setLayoutParams(new GridView.LayoutParams(200, 200));
                ///view.setScaleType(ImageView.ScaleType.CENTER_CROP);

           //     view.setPadding(8, 8, 8, 8);

           // }else{
            ///  view  = convertView;
           // }

                if(datalist[position][5].equals("")){
                im.setImageResource(R.drawable.image_fail);
            }else{

                Glide.with(getContext()).load(datalist[position][5])
                        .error(R.drawable.image_fail)
                        .into(im);

            }



            return view;
        }


    }
}
